/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-27 10:00:02
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-04-18 14:29:48
 * @FilePath: \vite-project\src\components\org\TenantOrgRole.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { getRolesByOrgIdOrAppId } from '@/apis/org';
import { Button, Form, Modal, Select, Space, Table, TreeSelect, message } from 'antd';
import React, { useEffect, useState } from 'react';

interface TenantOrgRoleProps {
	value?: any[];
	onChange?: (list: any[]) => void;
	treeData?: any[];
	parentNode: any;
}

const TenantOrgRole: React.FC<TenantOrgRoleProps> = ({ value = [], treeData = [], parentNode, onChange }) => {
	const columns = [
		{
			title: '组织机构',
			dataIndex: 'org',
			key: 'org',
			render: (_: any, record: { org: { label: any } }) => {
				return record?.org?.label;
			},
		},
		{
			title: '角色名字',
			dataIndex: 'role',
			key: 'role',
			render: (_: any, record: { role: { label: any } }) => {
				return record?.role?.label;
			},
		},
		{
			title: '操作',
			key: 'option',
			dataIndex: 'option',
			render: (text: any, record: any, index: any) => {
				return <a onClick={() => handleDel(index)}>删除</a>;
			},
		},
	];
	const [roleOptions, setRoleOptions] = useState<
		{
			label: string;
			value: string;
		}[]
	>([]);
	const [list, setList] = useState<any[]>([]);
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);
	const [open, setOpen] = useState(false);
	const org = Form.useWatch('org', form);

	const getRolesById = async () => {
		try {
			let res = await getRolesByOrgIdOrAppId({
				organizationId: org?.value,
			});
			setRoleOptions(
				(res.recordDatas || [])?.map((item: API.RolesByOrgIdOrAppIdResponseItem) => ({
					label: item.name || '',
					value: item.id || '',
				})),
			);
		} finally {
		}
	};
	const handleAdd = () => {
		setOpen(true);
		setTimeout(() => {
			form.setFieldValue('org', {
				value: parentNode?.id,
			});
		}, 500);
	};
	const hideModal = () => {
		setOpen(false);
		form.resetFields();
	};
	const handleDel = (index: number) => {
		const curList = list.filter((item, i) => i !== index);
		setList(curList);
		onChange?.(curList);
	};
	const onFinish = (form: any) => {
		const index = value?.findIndex(item => item?.role?.value === form?.role?.value);
		if (index >= 0) {
			message.error('该角色已被添加，请选择其他角色');
			return;
		}
		setLoading(true);
		const curList = [...list, form];
		setList(curList);
		onChange?.(curList);
		setLoading(false);
		setOpen(false);
	};

	useEffect(() => {
		if (org?.value) {
			getRolesById();
		}
	}, [org]);

	return (
		<>
			<div className="flex justify-end">
				<Button className="mb-12px" type="primary" onClick={handleAdd}>
					添加
				</Button>
			</div>
			<Table className="w-full" columns={columns} dataSource={value}></Table>
			<Modal destroyOnClose title="添加角色" open={open} onCancel={hideModal} width={500} centered footer={null}>
				<Form form={form} onFinish={onFinish}>
					<Form.Item name="org" label="组织机构" rules={[{ required: true, message: '请选择组织机构' }]}>
						<TreeSelect
							disabled
							labelInValue
							treeDefaultExpandAll
							className="w-240px"
							treeData={treeData}
							fieldNames={{
								label: 'name',
								value: 'id',
							}}
							placeholder="请选择组织机构"
							dropdownStyle={{ maxHeight: 500, minWidth: 300, overflow: 'auto' }}></TreeSelect>
					</Form.Item>
					<Form.Item name="role" label="角色" rules={[{ required: true, message: '请选择角色' }]}>
						<Select labelInValue placeholder="请选择角色" options={roleOptions}></Select>
					</Form.Item>
					<div className="flex justify-end">
						<Space align="end">
							<Button type="default" onClick={hideModal}>
								取消
							</Button>
							<Button type="primary" htmlType="submit" loading={loading}>
								提交
							</Button>
						</Space>
					</div>
				</Form>
			</Modal>
		</>
	);
};

export default TenantOrgRole;
